from Crypto.Cipher import AES

settings = None


class AESEncryptor(object):

    DEFAULT_KEY = b'nafasd31erqfdsafEdi3Fkld0aeifao23fdalhdsalf38207432h'[0:16]

    def __init__(self):
        key = self.DEFAULT_KEY
        self.cryptor = AES.new(key, AES.MODE_ECB)
        self.size = AES.block_size

    def _pad(self, text):
        pad_size = self.size - len(text) % self.size
        pad_text = text + pad_size * (chr(pad_size).encode('utf-8'))
        return pad_text

    def _unpad(self, text):
        return text[0:-ord(text[-1])]

    def encrypt(self, text):
        if not text:
            return ''
        if isinstance(text, (str, int, float)):
            text = str(text).encode('utf-8')
        text = self._pad(text)
        ciphertext = self.cryptor.encrypt(text).hex()
        return ciphertext

    def decrypt(self, text):
        if not text or text == 'None':
            return ''
        plain_text = self.cryptor.decrypt(bytes.fromhex(text))
        plain_text = self._unpad(plain_text.decode())
        return plain_text


aes_encryptor = AESEncryptor()
